﻿using Autofac.Integration.Mvc;
using Remember.Web.Models;
using Remember.Persistence;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Remember.Web.Binder
{
    /// <summary>
    /// 
    /// </summary>
    [ModelBinderType(typeof(LoginForm))]
    public class LoginFormBinder : IModelBinder
    {
        readonly IAuthentication _authService;

        public LoginFormBinder(IAuthentication authService)
        {
            _authService = authService;
        }

        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var model = new LoginForm();

            try
            {
                model.EmailAddress = bindingContext.ValueProvider.GetValue("Email").AttemptedValue;
                model.Password = bindingContext.ValueProvider.GetValue("Password").AttemptedValue;

                if (!_authService.IsValid(model.EmailAddress, model.Password))
                {
                    bindingContext.ModelState.AddModelError("", "登陆失败！");
                }
            }
            catch (Exception ex)
            {
                bindingContext.ModelState.AddModelError("", ex);
            }

            return model;
        }
    }
}